<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form
      ref="dataForm"
      :model="dataForm"
      :rules="dataRules"
      label-width="80px"
      @keyup.enter.native="dataFormSubmit()"
    >

      <el-form-item label="类型" prop="type">
        <el-radio-group v-model="dataForm.type">
          <el-radio v-for="(type, index) in dataForm.typeList" :key="index" :label="index">{{ type
          }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 根据上面的 类型 来显示对应名称 -->
      <el-form-item :label="dataForm.typeList[dataForm.type] + '名称'" prop="name">
        <el-input v-model="dataForm.name" :placeholder="dataForm.typeList[dataForm.type] + '名称'" />
      </el-form-item>

      <el-form-item label="上级菜单" prop="parentName">
        <el-input
          v-model="dataForm.parentName"
          v-popover:menuListPopover
          :readonly="true"
          placeholder="点击选择上级菜单"
        />
        <!-- elementui中的嵌套Popover 弹出框-->
        <el-popover ref="menuListPopover" placement="bottom-start" trigger="click">
          <!-- 参数说明:
						props(树形控件的主要属性配置)
						node-key(树形控件中的唯一标识)
						ref(引用名)
						@current-change(当前选中节点变化时触发的事件)
						default-expand-all(是否默认展开所有节点)
						expand-on-click-node(是否在点击节点的时候展开或者收缩节点,默认值为 true，如果为 false，则只有点箭头图标的时候才会展开或者收缩节点。)
						highlight-current(是否高亮当前选中节点,默认值是 false)
					-->
          <el-tree
            ref="listTree"
            :data="menuList"
            :props="listTreeProps"
            node-key="id"
            :default-expand-all="true"
            :highlight-current="true"
            :expand-on-click-node="false"
            @current-change="listTreeChangeHandle"
          />
        </el-popover>
      </el-form-item>

      <!-- 只能是 菜单 -->
      <el-form-item v-if="dataForm.type === 1" label="菜单路由" prop="path">
        <el-input v-model="dataForm.path" placeholder="菜单路由" />
      </el-form-item>

      <!-- 只能是 菜单 -->
      <el-form-item v-if="dataForm.type === 1" label="组件路径" prop="component">
        <el-input v-model="dataForm.component" placeholder="组件路径" />
      </el-form-item>

      <!-- 不能是 目录 类型,只能是 菜单 或 按钮 -->
      <el-form-item v-if="dataForm.type !== 0" label="授权标识" prop="perms">
        <el-input v-model="dataForm.perms" placeholder="类型(如btn):模块名:功能名,如: btn:menu:list" />
      </el-form-item>

      <!-- 按钮 不需要排序号 -->
      <el-form-item v-if="dataForm.type !== 2" label="排序号" prop="sortValue">
        <el-input-number
          v-model="dataForm.sortValue"
          controls-position="right"
          :min="0"
          label="排序号"
        />
      </el-form-item>

      <!-- 按钮 不需要图标 -->
      <el-form-item v-if="dataForm.type !== 2" label="菜单图标" prop="icon">
        <el-select v-model="dataForm.icon" clearable>
          <el-option v-for="item in iconList" :key="item.class" :label="item.class" :value="item.class">
            <span style="float: left;">
              <!-- 如果动态显示图标，这里添加判断 -->
              <i :class="item.class" />
            </span>
            <span style="padding-left: 6px;">{{ item.class }}</span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-switch
          v-model="dataForm.status"
          active-color="#13ce66"
          inactive-color="#ff4949"
          :inactive-value="0"
          :active-value="1"
        />
      </el-form-item>

    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import api from '@/api/system/menu'
// 这里的icons是自定义的图标数组,将其抽取出一个单独的js文件 然后引入
import icons from '@/utils/element-ui-icon'
// 菜单数据转换为树形结构(这个一定要加,不然没有如 'renren-fast-vue'demo中展示的效果)
import { translateTreeData } from '@/utils/index'
export default {
  data() {
    // 菜单path验证规则
    var validatePath = (rule, value, callback) => {
      if (this.dataForm.type === 1 && !/\S/.test(value)) {
        callback(new Error('菜单路由不能为空'))
      } else {
        callback()
      }
    }
    return {
      visible: false,
      dataForm: {
        id: 0,
        parentId: '',
        parentName: '',
        name: '',
        type: 1,
        typeList: ['目录', '菜单', '按钮'],
        path: '',
        component: '',
        perms: '',
        icon: '',
        sortValue: '',
        status: 1
      },
      // 图标
      iconList: [],
      // 上级菜单列表
      menuList: [],
      // 上级菜单 树形控件属性
      listTreeProps: {
        label: 'name',
        children: 'children'
      },
      // 验证规则
      dataRules: {
        name: [
          { required: true, message: '菜单名称不能为空', trigger: 'blur' }
        ],
        parentName: [
          { required: true, message: '上级菜单不能为空', trigger: 'change' }
        ],
        path: [
          { validator: validatePath, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 自定义图标列表
    this.iconList = icons.getIconList()
  },
  methods: {
    init(id) {
      this.dataForm.id = id || 0

      api.getNotButtonTypeMenuList().then(res => {
        this.menuList = translateTreeData(res.data, 'id')
      }).then(() => {
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
        })
      }).then(() => {
        if (this.dataForm.id) {
          api.getInfoById(id).then(res => {
            // console.log("id查询数据-----", res);
            this.dataForm.parentId = res.data.parentId
            this.dataForm.name = res.data.name
            this.dataForm.type = res.data.type
            this.dataForm.path = res.data.path
            this.dataForm.component = res.data.component
            this.dataForm.perms = res.data.perms
            this.dataForm.icon = res.data.icon
            this.dataForm.sortValue = res.data.sortValue
            this.dataForm.status = res.data.status

            this.listTreeSetCurrentNode()
          })
        } else {
          // 加了这段代码,表示在 第一次新增或修改的时候,选择完'上级菜单'的值后,第二次打开弹窗继续显示上一次选择的上级菜单的值
          // 如果不想显示上一次选择上级菜单的值,可以删除这个else代码块
          this.listTreeSetCurrentNode()
        }
      })
    },
    // 树形控件节点改变事件
    listTreeChangeHandle(data, node) {
      this.dataForm.parentId = data.id
      this.dataForm.parentName = data.name

      if (this.dataForm.type === 0 || this.dataForm.type === 1) {
        if (data.id === 0) {
          // 如果选择的菜单类型是'菜单',且是'一级菜单'
          this.dataForm.component = 'Layout'
        } else if (data.id === 1) {
          this.dataForm.component = 'ParentView'
        } else {
          this.dataForm.component = ''
        }
      } else {
        this.dataForm.component = ''
      }
    },
    // 为 this.dataForm.parentName 设置
    listTreeSetCurrentNode() {
      // setCurrentKey是 el-tree中的属性方法
      this.$refs.listTree.setCurrentKey(this.dataForm.parentId)
      // this.$refs.listTree.getCurrentNode() 表示获取选中的节点信息
      this.dataForm.parentName = (this.$refs.listTree.getCurrentNode() || {})['name']
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          api.editData({
            'id': this.dataForm.id || undefined,
            'parentId': this.dataForm.parentId,
            'name': this.dataForm.name,
            'type': this.dataForm.type,
            'path': this.dataForm.path,
            'component': this.dataForm.component,
            'perms': this.dataForm.perms,
            'icon': this.dataForm.icon,
            'sortValue': this.dataForm.sortValue,
            'status': this.dataForm.status
          }, !this.dataForm.id ? 'save' : 'update').then(res => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.visible = false
                this.$emit('refreshDataList')
              }
            })
          })
        }
      })
    }
  }
}
</script>

<style>

</style>
